package mil.af.amc.adpetracker.web.actions.struts1.AdpeAccount.ajax;

import mil.af.amc.adpetracker.model.AdpeAccount;
import mil.af.amc.adpetracker.service.AdpeAccountService;
import mil.af.amc.adpetracker.web.actions.struts1.AbstractAction;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Action to get an individual AdpeAccount object, convert it to JSON, and return it.
 *
 * @author TSgt Jason Ferguson
 */

public class GetAdpeAccountByIdAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(GetAdpeAccountByIdAction.class);

    private AdpeAccountService adpeAccountService;

    public void setAdpeAccountService(AdpeAccountService adpeAccountService) {
        this.adpeAccountService = adpeAccountService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        int adpeAccountId = Integer.parseInt(httpServletRequest.getParameter("adpeAccountId"));
        AdpeAccount acct = adpeAccountService.getById(adpeAccountId);

        // Hack to prevent to "cycle in the hierarchy" exception. AdpeAccount implements the MappableEntity
        // interface for this reason
        JSONObject jsonObject = JSONObject.fromObject(acct.toMap());

        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().println(jsonObject);

        return null;
    }
}
